package org.example;

import javax.net.ssl.*;
import java.io.FileInputStream;
import java.security.KeyStore;

/**
 * @author hh
 * @since 2025/2/16
 */
public class SSLTest {

    public static void main(String[] args) throws Exception {
        // 仓库密钥
        String pass = "123456";
        String keyStoreFile = "/Users/hh/test/server.jks";
        char[] passArray = pass.toCharArray();
        KeyStore keyStore = KeyStore.getInstance("JKS");
        // 加载keyStoreFile，生成的密钥仓库
        try (FileInputStream fis = new FileInputStream(keyStoreFile)){
            keyStore.load(fis, passArray);
        }

        // 创建密钥管理器，并且初始化
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, passArray);

        // 信任库，如果是单向认证，服务端不需要验证客户端的合法性，此时TrustManager可以为空
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        // 初始化KeyManagerFactory之后，创建SSLContext并初始化
        SSLContext sslContext = SSLContext.getInstance("SSL");
        // 安全随机数不需要设置
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        SSLServerSocketFactory sslContextServerSocketFactory = sslContext.getServerSocketFactory();
        // 通过服务端SSL上下文实例创建服务端SSL监听套接字
        SSLServerSocket sslServerSocket = ((SSLServerSocket) sslContextServerSocketFactory.createServerSocket(8080));
    }
}
